package com.example.mybatisplusdemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplusdemo.mapper.FlightMapper;
import com.example.mybatisplusdemo.model.domain.Flight;
import com.example.mybatisplusdemo.model.domain.ItineraryRequest;
import com.example.mybatisplusdemo.model.domain.SegmentRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FlightSearchService {
    private final FlightMapper flightMapper;

    public List<Flight> searchFlights(ItineraryRequest request) {
        // 1. 构建行程段查询条件
        List<SegmentRequest> segments = request.getSegments();
        List<QueryWrapper<Flight>> segmentQueries = new ArrayList<>();

        for (SegmentRequest segment : segments) {
            QueryWrapper<Flight> segmentWrapper = new QueryWrapper<>();

            // 基础条件
            segmentWrapper.eq("departure_airport_code", segment.getOriginAirportCode());
            segmentWrapper.eq("arrival_airport_code", segment.getDestinationAirportCode());
            segmentWrapper.between("departure_time",
                    segment.getDepartureDate().atStartOfDay(),
                    segment.getDepartureDate().atTime(LocalTime.MAX));

            // 中转过滤
            applyTransferFilters(segmentWrapper, segment, request);
            segmentQueries.add(segmentWrapper);
        }

        // 2. 构建全局查询条件
        QueryWrapper<Flight> globalWrapper = new QueryWrapper<>();
        applyGlobalFilters(globalWrapper, request);

        // 3. 组合查询条件并执行
        return flightMapper.selectFlightsByItinerary(segmentQueries, globalWrapper, request);
    }

    private void applyTransferFilters(QueryWrapper<Flight> wrapper, SegmentRequest segment, ItineraryRequest request) {
        // 中转城市过滤
        if (request.getIncludeTransferCities() != null) {
            wrapper.apply("JSON_CONTAINS(transfer_cities, '" +
                    String.join(",", request.getIncludeTransferCities()) + "')");
        }
        if (request.getExcludeTransferCities() != null) {
            wrapper.apply("NOT JSON_CONTAINS(transfer_cities, '" +
                    String.join(",", request.getExcludeTransferCities()) + "')");
        }

        // 中转时间过滤
        if (segment.getTransferOptions() != null) {
            segment.getTransferOptions().forEach(transfer -> {
                wrapper.apply("transfer_cities LIKE '%" + transfer.getAirportCode() + "%'");
                wrapper.between("arrival_time",
                        LocalDateTime.now().plusMinutes(transfer.getMinMinutes()),
                        LocalDateTime.now().plusMinutes(transfer.getMaxMinutes()));
            });
        }
    }

    private void applyGlobalFilters(QueryWrapper<Flight> wrapper, ItineraryRequest request) {
        // 基础条件
        wrapper.eq("service_class", request.getCabinClass());
        wrapper.le("carbon_emission", request.getMaxCarbon());
        wrapper.ge("punctuality_rate", request.getMinPunctuality());
        wrapper.ge("seat_comfort", request.getMinComfort());

        // 价格范围
        if (request.getMinPrice() != null || request.getMaxPrice() != null) {
            wrapper.between("price",
                    request.getMinPrice() != null ? request.getMinPrice() : 0,
                    request.getMaxPrice() != null ? request.getMaxPrice() : BigDecimal.valueOf(100000));
        }

        // 航空公司过滤
        if (request.getAirlines() != null) {
            wrapper.in("airline_code", request.getAirlines());
        }
    }
}